<?php
/**
 * SellerCategoryRepo.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-07-26 17:45:41
 * @modified   2023-07-26 17:45:41
 */

namespace Beike\Seller\Repositories;

use Beike\Seller\Models\SellerCategory;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Throwable;

class SellerCategoryRepo
{
    private static array|null $allCategoryWithName = null;

    /**
     * 获取分类列表
     *
     * @param int   $sellerId
     * @param array $filters
     * @return Builder[]|Collection
     */
    public static function list(int $sellerId, array $filters = []): Collection|array
    {
        $builder = self::getBuilder($sellerId, $filters)->with('description');

        return $builder->get();
    }

    /**
     * 获取筛选builder
     *
     * @param int   $sellerId
     * @param array $filters
     * @return Builder
     */
    public static function getBuilder(int $sellerId, array $filters = []): Builder
    {
        $builder = SellerCategory::query()->with(['description'])
            ->where('seller_id', $sellerId);
        $keyword = $filters['keyword'] ?? '';
        if ($keyword) {
            $builder->whereHas('description', function ($query) use ($keyword) {
                return $query->where('name', 'like', "%$keyword%");
            });
        }
        if (isset($filters['active'])) {
            $builder->where('active', $filters['active'] ?: 0);
        }

        return $builder;
    }

    /**
     * 创建一个记录
     * @param int   $sellerId
     * @param array $data
     * @return SellerCategory
     * @throws Throwable
     */
    public static function create(int $sellerId, array $data): SellerCategory
    {
        $sellerCategory = new SellerCategory([
            'seller_id'   => $sellerId,
            'parent_id'   => $data['parent_id'] ?? 0,
            'position'    => $data['position'],
            'active'      => $data['active'],
        ]);
        $sellerCategory->saveOrFail();

        $descriptions = [];
        foreach ($data['descriptions'] as $locale => $description) {
            $description['locale'] = $locale;
            $descriptions[]        = $description;
        }
        $sellerCategory->descriptions()->createMany($descriptions);

        return $sellerCategory;
    }

    /**
     * @param int   $sellerId
     * @param int   $id
     * @param array $data
     * @return Model|Collection|Builder|array
     * @throws Exception
     */
    public static function update(int $sellerId, int $id, array $data): Model|Collection|Builder|array
    {
        $sellerCategory = SellerCategory::query()->find($id);
        if (! $sellerCategory || $sellerCategory->seller_id != $sellerId) {
            throw new Exception("Seller Category id $id 不存在");
        }
        $sellerCategory->update($data);

        $sellerCategory->descriptions()->delete();
        $descriptions = [];
        foreach ($data['descriptions'] as $locale => $description) {
            $description['locale'] = $locale;
            $descriptions[]        = $description;
        }

        $sellerCategory->descriptions()->createMany($descriptions);

        return $sellerCategory;
    }

    /**
     * @param $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public static function find($id): Model|Collection|Builder|array|null
    {
        return SellerCategory::query()->find($id);
    }

    /**
     * 删除分类
     * @param $sellerId
     * @param $id
     * @return void
     */
    public static function delete($sellerId, $id): void
    {
        $category = SellerCategory::query()->where('seller_id', $sellerId)->findOrFail($id);
        if (! $category) {
            return;
        }
        $category->descriptions()->delete();
        $category->productCategories()->delete();
        $category->delete();
    }

    /**
     * 通过分类ID获取分类名称
     * @param $sellerId
     * @param $category
     * @return mixed|string
     */
    public static function getName($sellerId, $category): mixed
    {
        $id         = is_int($category) ? $category : $category->id;
        $categories = self::getAllCategoriesWithName($sellerId);

        return $categories[$id]['name'] ?? '';
    }

    /**
     * 获取所有商品分类ID和名称列表
     * @param $sellerId
     * @return array|null
     */
    public static function getAllCategoriesWithName($sellerId): ?array
    {
        if (self::$allCategoryWithName !== null) {
            return self::$allCategoryWithName;
        }

        $items      = [];
        $categories = self::getBuilder($sellerId)->select('id')->get();
        foreach ($categories as $category) {
            $items[$category->id] = [
                'id'   => $category->id,
                'name' => $category->description->name ?? '',
            ];
        }

        return self::$allCategoryWithName = $items;
    }
}
